<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\cms\controller;

use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\admin\service\AdminService;
use think\admin\service\MenuService;
use think\facade\Config;


/**
 * 栏目管理
 * Class Menu
 * @package app\admin\controller
 */
class Category extends Controller
{

    /**
     * 当前操作数据库
     * @var string
     */
    protected $table = 'CmsCategory';
    protected $tables = 'CmsArticles';
    public $privacy = array(0=>"公开",1=>"私密");

    /**
     * 栏目管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->types = Config::get('app.category_type');
        $this->title = '栏目管理';

        $map = [ "is_deleted" => 0 ];
        $this->_query($this->table)->where($map)->page(false);
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(&$data)
    {
        foreach ($data as &$vo) {
            $vo['ids'] = join(',', DataExtend::getArrSubIds($data, $vo['id'], $key = 'id', $pkey = 'parent_id'));
        }
        $data = DataExtend::arr2table($data, $key="id", $pkey="parent_id");
    }

    /**
     * 添加栏目
     * @auth true
     */
    public function add()
    {

        if ($this->request->isGet()) {
            $this->_applyFormToken();
            $this->_form($this->table, 'form');
        } else {
            $update = [
                'create_by'  => AdminService::instance()->getUserId(),
                "title"  => $this->request->post('title'),
                "parent_id"  => $this->request->post('parent_id'),
                'type' => $this->request->post('type'),
                'create_at' => time(),
            ];
            $id = $this->app->db->name($this->table)->insertGetId($update);
            if ($id <= 0 ) {
                $this->error('栏目添加失败，请稍候再试！');
           }
            if($update['type']!='info')
                $this->success('栏目添加成功！');
           $article = array("title"=>$update['title'],"type"=>$update['type'], "category_id"=>$id);
            if ($this->app->db->name('CmsArticles')->insert($article)){
                $this->success('栏目添加成功！');
           } else {
               $this->error('栏目添加失败，请稍候再试！');
            }

        }
    }

    /**
     * 编辑栏目
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->_applyFormToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 表单数据处理
     * @param array $vo
     * @throws \ReflectionException
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            // 清理权限节点
            AdminService::instance()->clearCache();
            // 读取系统功能节点
            $this->nodes = MenuService::instance()->getList();
            // 选择自己的上级菜单
            if (empty($vo['parent_id']) && $this->request->get('parent_id', '0')) $vo['parent_id'] = $this->request->get('parent_id', '0');
            // 列出可选上级菜单
            $menus = $this->app->db->name($this->table)->where(['status' => '1'])->order('sort desc,id asc')->column('id,parent_id,title,memo,type', 'id');

            $this->menus = DataExtend::arr2table(array_merge($menus, [['id' => '0', 'parent_id' => '-1', 'title' => '顶级分类']]),$key="id",$pkey="parent_id");
            if (isset($vo['id'])) foreach ($this->menus as $key => $menu) if ($menu['id'] === $vo['id']) $vo = $menu;
            foreach ($this->menus as $key => &$menu) {
                if ($menu['spt'] >= 3) unset($this->menus[$key]);
                if (isset($vo['spt']) && $vo['spt'] <= $menu['spt']) unset($this->menus[$key]);
            }
            $this->types = Config::get('app.category_type');
        }
    }

    /**
     * 修改菜单状态
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_applyFormToken();
        $this->_save($this->table, ['status' => intval(input('status'))]);
    }

    /**
     * 删除栏目
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
       $this->_applyFormToken();
       $this->id= $this->request->post('id');
        $this->parent_id=$this->request->post('parent_id');
        $map = ['category_id' =>$this->id];
       $this->app->db->name('CmsArticles')->where($map)->delete();
        $this->_delete($this->table);

    }

    /**
     * 设为公开
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function setPublic()
    {
        $this->_save($this->table, ['is_private' => intval(input('private'))]);
    }

}
